package cn.itcast.storage.config;

import com.alibaba.druid.pool.DruidDataSource;
import io.seata.core.exception.TransactionException;
import io.seata.core.model.BranchType;
import io.seata.spring.annotation.datasource.DataSourceProxyHolder;
import io.seata.tm.api.GlobalTransaction;
import io.seata.tm.api.GlobalTransactionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Configuration
public class SeataConfig {

    @Autowired
    private DruidDataSource dataSource;

    // 启动时主动初始化 Seata 客户端
    @PostConstruct
    public void initSeata() {

        try {
            // 预热连接池
            DataSourceProxyHolder.get().putDataSource(dataSource, BranchType.TCC);
            // 模拟空事务预热
            GlobalTransaction tx = GlobalTransactionContext.getCurrentOrCreate();
            tx.begin(30000, "preheat-tx");
            tx.commit();
        } catch (TransactionException e) {
            throw new RuntimeException(e);
        }
    }

}
